/*
 * $Id: QENSStringExtension.m 248 2008-09-08 15:31:38Z+ jon $
 * Sleeper
 *
 * Created by Jon Gordon on 1/20/08
 * Copyright Jon Gordon.  All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining 
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including 
 * without limitation the rights to use, copy, modify, merge, publish, 
 * distribute, sublicense, and/or sell copies of the Software, and to 
 * permit persons to whom the Software is furnished to do so, subject to 
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */


#import <Foundation/Foundation.h>

#import "QENSStringExtension.h"

static const unichar CR = '\r';
static const unichar LF = '\n';

@implementation NSString (QEExtension)
- (NSString *)stringByTrimmingLeadingCharsFromSet:(NSCharacterSet *)cs
{
    unsigned int csLen = [self length];
    unsigned int i = 0;
    
    while ((i < csLen) && ([cs characterIsMember:[self characterAtIndex:i]])) {
        ++i;
    } // while
    
    return [self substringFromIndex:i];
} // stringByTrimmingLeadingCharsFromSet:

- (NSString *)stringByTrimmingTrailingCharsFromSet:(NSCharacterSet *)cs
{
    unsigned int i = ([self length] - 1);
    
    while ((i >= 0) && ([cs characterIsMember:[self characterAtIndex:i]])) {
        --i;
    } // while
    
    return [self substringToIndex:(i + 1)];
} // stringByTrimmingTrailingCharsFromSet:

- (NSString *)chop
{
    NSString *result;
    if (0 == [self length]) {
        result = self;
    } else {
        result = [self substringToIndex:([self length] - 1)];
    } // else
    return result;
} // chop

- (NSString *)chomp
{
    unsigned int index = [self length] - 1;
    if (index < 0) {
        return self;
    } // if
    
    if ([self characterAtIndex:index] == LF) {
        --index;
    } // if
    if ((index >= 0) && ([self characterAtIndex:index] == CR)) {
        --index;
    } // if
    
    return [self substringToIndex:(index + 1)];
} // chomp
@end
